package com.situ.mall.admin.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import com.situ.mall.common.util.CommonUtil;
import com.situ.mall.common.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/admin")
public class CaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisTemplate redisTemplate;
    //图片以json形式返回
    @GetMapping("/captcha")
    public Result getCaptcha(HttpServletRequest request , HttpServletResponse response) throws IOException {
        //这一段不懂是什么意思
        System.out.println("KaptchaController.kaptcha");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //用工具类生成文字
        String kaptchaText = defaultKaptcha.createText();
        System.out.println("kaptchaText:" + kaptchaText);
        //redis存储   60*1000*10 失效时间10分钟
        redisTemplate.opsForValue().set(getCaptchaKey(request), kaptchaText, 60 * 1000 * 10, TimeUnit.MILLISECONDS);
        //用工具类生成图片
        BufferedImage kaptchaImage = defaultKaptcha.createImage(kaptchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(kaptchaImage, "jpg", outputStream);
        //用base64编码,把图片生成字符串
        String base64Code = Base64.encodeBase64String(outputStream.toByteArray());

        return Result.ok("", "data:image/png;base64," + base64Code);
    }

    /**
     * 获取缓存的key
     *
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        //获取ip
        String ip = CommonUtil.getIpAddr(request);
        //浏览器识别
        String userAgent = request.getHeader("User-Agent");
        String key = "captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("key:{},ip:{},userAgent:{}", key, ip, userAgent);
        return key;
    }
}
